<template>
  <PageWrapper dense fixedHeight contentClass="flex">
    <!-- <PageWrapper dense contentFullHeight fixedHeight contentClass="flex"> -->
    <DeptTree class="w-1/4 xl:w-1/5" @select="handleSelect" />
    <BasicTable
      @register="registerTable"
      class="w-3/4 xl:w-4/5"
      :pagination="false"
      :searchInfo="searchInfo"
    >
      <!-- 标记 -->
      <template #statusFlag="{ record }">
        <template v-if="record.flag == 0">
          <Tag :color="'green'">启用</Tag>
        </template>
        <template v-if="record.flag == 5">
          <Tag :color="'yellow'">禁用</Tag>
        </template>
        <template v-if="record.flag == 9">
          <Tag :color="'red'">已删除</Tag>
        </template>
      </template>

      <template #toolbar>
        <a-button type="primary" @click="onAddUser">新增用户</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'clarity:note-edit-line',
                tooltip: '编辑',
                onClick: onEditUser.bind(null, record),
              },
              {
                icon: 'ant-design:delete-outlined',
                color: 'error',
                tooltip: '删除',
                popConfirm: {
                  title: '是否确认删除',
                  placement: 'left',
                  confirm: onDeleteUser.bind(null, record),
                },
              },
              {
                icon: 'ant-design:lock-outlined',
                tooltip: '重置密码',
                popConfirm: {
                  title: '是否确认重置密码',
                  placement: 'left',
                  confirm: resetPwd.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <addOrUpdateUser @register="registerAddOrUpdateUserForm" @success="afterSuccess" />
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, reactive, provide, ref } from 'vue';

  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { Tag } from 'ant-design-vue';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { PageWrapper } from '/@/components/Page';

  import DeptTree from './DeptTree.vue';

  import { useModal } from '/@/components/Modal';
  import addOrUpdateUser from './AddOrUpdateDeptUser.vue';

  import { queryProjectUsersDetail, deleteProjectUser, resetPassword } from '/@/api/project/user';
  import { userTableColumns, projectUserQueryConditionFormSchema } from './deptuser.data';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { t } from '/@/hooks/web/useI18n';
  const { createMessage, createSuccessModal } = useMessage();

  import { useCopyToClipboard } from '/@/hooks/web/useCopyToClipboard';
  const { clipboardRef } = useCopyToClipboard();

  const [registerAddOrUpdateUserForm, { openModal: openAddOrUpdateForm }] = useModal();

  export default defineComponent({
    name: 'AccountManagement',
    components: {
      BasicTable,
      PageWrapper,
      DeptTree,
      addOrUpdateUser,
      TableAction,
      Tag,
    },
    setup() {
      //定义模块的名称，提供给子孙组件获取使用
      const moduleName = ref('用户管理');
      provide('moduleName', moduleName);

      //点击部门获取的部门id用于查询部门用户的条件
      const searchInfo = reactive<Recordable>({});

      //查询表单中的项目编码
      const pcode = ref('');

      const [registerTable, { reload }] = useTable({
        title: '用户管理',
        api: queryProjectUsersDetail,
        rowKey: 'id',
        columns: userTableColumns,
        beforeFetch: (searchData) => {
          pcode.value = searchData.project;
          searchData.includedelete = false;
        },
        formConfig: {
          labelWidth: 80,
          schemas: projectUserQueryConditionFormSchema,
          autoSubmitOnEnter: true,
        },
        useSearchForm: true,
        showTableSetting: true,
        bordered: true,
        striped: false,
        canResize: true,
        actionColumn: {
          width: 120,
          title: '操作',
          dataIndex: 'action',
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
      });

      /**
       * 打开新增窗口,将左侧选中的部门id传过去，默认所属部门为左侧选中部门
       */
      function onAddUser() {
        openAddOrUpdateForm(true, { op: OperationTypeEnum.ADD, deptId: searchInfo.dept });
      }

      /**
       * 打开编辑窗口
       */
      function onEditUser(record: Recordable) {
        openAddOrUpdateForm(true, { op: OperationTypeEnum.EDIT, dataId: record.id });
      }

      /**
       * 删除
       */
      function onDeleteUser(record: Recordable) {
        deleteProjectUser({ id: record.id, project: pcode.value })
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('删除成功。', 2);
              afterSuccess();
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 重置密码
       */
      function resetPwd(record: Recordable) {
        resetPassword(record.id)
          .then((res) => {
            console.log('res', res);
            if (res.success) {
              // createMessage.success('重置密码成功', 2);
              createSuccessModal({
                title: t('重置密码成功'),
                content: '成功重置密码为：' + res.pwd + ' 密码已复制到剪贴板，可以直接粘贴使用。',
              });
              clipboardRef.value = res.pwd; //将密码复制到剪贴板
              afterSuccess();
            } else {
              createMessage.error('重置密码失败', 2);
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 点击部门获取部门id
       * @param dept 部门id
       */
      function handleSelect(dept = '') {
        searchInfo.dept = dept;
        // console.log('部门id', searchInfo.dept);
        reload();
      }

      /**
       * 弹窗确认操作之后刷新页面
       */
      function afterSuccess() {
        reload();
      }

      return {
        registerTable,
        registerAddOrUpdateUserForm,
        handleSelect,
        searchInfo,
        afterSuccess,
        onAddUser,
        onEditUser,
        onDeleteUser,
        resetPwd,
      };
    },
  });
</script>
